logo头像
Snippet 博客主题

React Native如何消除启动时白屏

本文于473天之前发表,文中内容可能已经过时。

在RN 项目启动之后有一个短暂的白屏,调试阶段白屏的时间较长,大概3-5秒,打正式包后这个白屏时间会大大缩短,大多时候都是一闪而过,所以称之为“闪白”。
这里写图片描述这里写图片描述

其实解决的方案也有很多,这里做一个简单的总结。

白屏的原因

在iOS App 中有 启动图(LaunchImage),启动图结束后才会出现上述的闪白,这个过程是 JS 解释的过程,JS 解释完毕之前没有内容,所以才表现出白屏,那么解决的方法就是在启动图结束后,JS 解释完成前做一些简单的处理。

解决的常见方案:

  1. 启动图结束后通过原生代码加载一张全屏占位图片,跟启动图一样的图片,混淆视听“欺骗用户”。
  2. JS解释完毕后通知原生可以移除占位图
  3. 收到 JS 发来的可以移除占位图的通知,移除占位图

代码实现

新建一个SplashScreen 文件用来接收 JS 发来的”移除占位图”的消息。相关代码如下:
SplashScreen.h

1
2
3
4
5
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
@interface SplashScreen : NSObject<RCTBridgeModule>
@end

SplashScreen.m

1
2
3
4
5
6
7
8
9
#import "SplashScreen.h"
@implementation SplashScreen
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(close){
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_CLOSE_SPLASH_SCREEN" object:nil];
}
@end

在AppDelegate.m 加入以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@interface AppDelegate ()
{
UIImageView *splashImage;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeSplashImage) name:"Notification_CLOSE_SPLASH_SCREEN" object:nil];
...
[self autoSplashScreen];//写在 return YES 之前,其他代码之后
return YES;
}
-(void)autoSplashScreen {
if (!splashImage) {
splashImage = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
}
if (IPHONESCREEN3p5) {
[splashImage setImage:[UIImage imageNamed:@"launch4"]];
}else if (IPHONESCREEN4){
[splashImage setImage:[UIImage imageNamed:@"launch5"]];
}else if (IPHONESCREEN4p7){
[splashImage setImage:[UIImage imageNamed:@"launch6"]];
}else if (IPHONESCREEN5p5){
[splashImage setImage:[UIImage imageNamed:@"launch7"]];
}
[self.window addSubview:splashImage];
}
-(void)closeSplashImage {
dispatch_sync(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.5 animations:^{
splashImage.alpha = 0;
} completion:^(BOOL finished){
[splashImage removeFromSuperview];
}];
});
}

在合适的时机选择移除占位图。js端代码:

1
2
3
if (Platform.OS === 'ios') {
NativeModules.SplashScreen.close();
};

更加详细的信息可以访问:https://github.com/crazycodeboy/react-native-splash-screen/blob/master/README.zh.md

支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

上一篇